package cn.hxzy.ssoserver.filter;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class ClientFilter implements Filter {
    public ClientFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        if (!StringUtils.isEmpty(req.getRequestURI()) && req.getRequestURI().endsWith("/login.html")) {
            String token = (String) session.getAttribute("token");
            if (!StringUtils.isEmpty(token)) {
                resp.sendRedirect(request.getParameter("redirectUrl") + "?token=" + token);
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}
